﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace SHFST.Core
{
    class ScrollingBackground
    {
        private Point screenPos, origin, texturesize;
        private Texture2D myTexture;
        private int screenwidth;

        public void Load(GraphicsDevice device, Texture2D backgroundTexture)
        {
            myTexture = backgroundTexture;
            int screenHeight = device.Viewport.Height;
            screenwidth = device.Viewport.Width;
            origin = new Point(0, myTexture.Height / 2);
            // Set the screen position to the center of the screen.
            screenPos = new Point(0, screenHeight / 2);
            // Offset to draw the second texture, when necessary.
            texturesize = new Point(0, myTexture.Height);
        }

        public void Update(int deltaX)
        {
            screenPos.X += deltaX;
            screenPos.X = screenPos.X % myTexture.Width;
            if (screenPos.X < -myTexture.Width)
            {
                screenPos.X = 0;
            }
        }

        public void Draw(SpriteBatch batch)
        {
            batch.Draw(myTexture, new Vector2 (screenPos.X, screenPos.Y), null,
                 Color.White, 0, new Vector2 (origin.X, origin.Y), 1, SpriteEffects.None, 0f);
            if (screenPos.X < screenwidth - myTexture.Width)
            {
                batch.Draw(myTexture, new Vector2 (screenPos.X + myTexture.Width, screenPos.Y), null,
                           Color.White, 0, new Vector2 (origin.X, origin.Y), 1, SpriteEffects.None, 0f);
            }
            // Draw the texture a second time, behind the first,
            // to create the scrolling illusion.
            batch.Draw (myTexture, new Vector2 (screenPos.X - texturesize.X, screenPos.Y - texturesize.Y), null,
                        Color.White, 0, new Vector2 (origin.X, origin.Y), 1, SpriteEffects.None, 0f);
        }
    }
}
